package com.top.mall.main.mine

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import android.webkit.*
import androidx.annotation.RequiresApi
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewModeActivity
import com.top.mall.R
import com.top.mall.base.BaseViewModel
import com.top.mall.custom.setTransitionStatus
import kotlinx.android.synthetic.main.activity_mine_rich_text.*

enum class Agree(val title: String, val type: String) {
    AGREEMENT_YHXY("用户协议", "yhxy"),
    AGREEMENT_YSZC("隐私协议", "yszc"),
    AGREEMENT_MZSM("免责声明", "mzsm")
}

class MineRichTextActivity : OwnerViewModeActivity<BaseViewModel>() {

    companion object {
        private const val EXTRA_KEY_TITLE = "EXTRA_KEY_TITLE"
        private const val EXTRA_KEY_URL = "EXTRA_KEY_URL"
        private const val EXTRA_KEY_CONTENT = "EXTRA_KEY_CONTENT"
        private const val EXTRA_KEY_TYPE = "EXTRA_KEY_TYPE"

        fun openUrl(title: String? = null, url: String?) {
            val bundle = Bundle().apply {
                putString(EXTRA_KEY_TITLE, title)
                putString(EXTRA_KEY_URL, url)
            }
            ActivityUtils.startActivity(bundle, MineRichTextActivity::class.java)
        }

        fun openCon(title: String? = null, content: String?) {
            val bundle = Bundle().apply {
                putString(EXTRA_KEY_TITLE, title)
                putString(EXTRA_KEY_CONTENT, content)
            }
            ActivityUtils.startActivity(bundle, MineRichTextActivity::class.java)
        }

        fun openApi(title: String? = null, type: String?) {
            val bundle = Bundle().apply {
                putString(EXTRA_KEY_TITLE, title)
                putString(EXTRA_KEY_TYPE, type)
            }
            ActivityUtils.startActivity(bundle, MineRichTextActivity::class.java)
        }
    }

    private val mTitle: String?
        get() = intent?.extras?.getString(EXTRA_KEY_TITLE)

    private val mUrl: String?
        get() = intent?.extras?.getString(EXTRA_KEY_URL)

    private val mContent: String?
        get() = intent?.extras?.getString(EXTRA_KEY_CONTENT)

    private val mType: String?
        get() = intent?.extras?.getString(EXTRA_KEY_TYPE)

    override fun viewModel(): BaseViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_mine_rich_text

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = true, view = flRichTextBar)
    }

    @SuppressLint("JavascriptInterface")
    override fun initView() {

        imageViewBack.setOnClickListener { this.finish() }


        flRichTextBar.visibility = if (mTitle.isNullOrEmpty())
            View.GONE else View.VISIBLE

        textViewTitle.text = mTitle

        wvRichTextWeb.webViewClient = WebViewClient()
//        wvRichTextWeb.addJavascriptInterface(JsInterfaceObject(), JsInterfaceObject.NAME)
        wvRichTextWeb.settings.apply {
            //支持缩放，默认为true。
            setSupportZoom(false)
            //调整图片至适合webview的大小
            useWideViewPort = true
            // 缩放至屏幕的大小
            loadWithOverviewMode = true
            //设置默认编码
            defaultTextEncodingName = "utf-8"
            //设置自动加载图片
            loadsImagesAutomatically = true
            //允许访问文件
            allowFileAccess = true
            //开启javascript
            javaScriptEnabled = true
            //支持通过JS打开新窗口
            javaScriptCanOpenWindowsAutomatically = true
            //支持内容重新布局
            layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN;
            //关闭webview中缓存
            cacheMode = WebSettings.LOAD_NO_CACHE
        }

//        wvRichTextWeb.webChromeClient = object : WebChromeClient() {
//            override fun onProgressChanged(view: WebView?, newProgress: Int) {
//                super.onProgressChanged(view, newProgress)
//                LogUtils.e("==========${newProgress}")
//            }
//        }

        wvRichTextWeb.webViewClient = object : WebViewClient() {
            @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
            override fun shouldOverrideUrlLoading(
                view: WebView?, request: WebResourceRequest?
            ): Boolean {
                if (request == null) {
                    return false
                }
                try {
                    val url = request.url.toString()
                    if (url.startsWith("http:") || url.startsWith("https:")) {
                        return false
                    }
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    startActivity(intent)
                } catch (e: Exception) {
                    return false
                }
                return true
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                if (url == null) {
                    return false
                }
                try {
                    if (url.startsWith("http:") || url.startsWith("https:")) {
                        return false
                    }
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    startActivity(intent)
                } catch (e: Exception) {
                    return false
                }
                return true
            }
        }

    }

    override fun initData() {
        mUrl?.let {
            wvRichTextWeb.loadUrl(it)
        }
        mContent?.let {
            wvRichTextWeb.loadDataWithBaseURL((""), it, ("text/html"), ("utf-8"), (null))
        }

        mType?.let {
            viewModel.userAbout(it)
        }

    }

    override fun initViewMode() {
        viewModel.userAboutLiveData.observe(this as LifecycleOwner, { response ->
            this.setTransitionStatus(response)
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            wvRichTextWeb.loadDataWithBaseURL(
                (""), data.content, ("text/html"), ("utf-8"), (null)
            )
        })
    }

}
